package first.progr.helpstaff;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import first.progr.tc.ContactData;
import first.progr.utils.SortedListOf;

public class ContactHelper extends HelperBase{
    
	public static boolean CREATION = true;
	public static boolean MODIFICATION = false;
	
	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
    
	private SortedListOf<ContactData> cachedCont;
	
	public SortedListOf<ContactData> getContacts() {
		if (cachedCont == null) {
			rebuildCache();
		}
		return cachedCont;
     }
	
	private void rebuildCache() {
		cachedCont = new SortedListOf<ContactData>();
		manager.navigateTo().mainPage();
		List<WebElement> tRows = driver.findElements(By.xpath("//tr[@name='entry']"));		
		for (int trIndex = 0; trIndex < tRows.size(); trIndex++) {
		    WebElement element = tRows.get(trIndex);
		    String locator = "//tr[" + (trIndex+2) +"]//td[%s]";
		    String lname = element.findElement(By.xpath(String.format(locator, 2))).getText();
		    String fname = element.findElement(By.xpath(String.format(locator, 3))).getText();
		    String em = element.findElement(By.xpath(String.format(locator, 4))).getText();
		    String ph = element.findElement(By.xpath(String.format(locator, 5))).getText();
		    cachedCont.add(new ContactData().withFitstName(fname).withLastName(lname).withMainEmail(em).withHomePhone(ph));
		}
	}
	
	public SortedListOf<ContactData> getContacts2(){
		SortedListOf<ContactData> lst1 = new SortedListOf<ContactData>();
		manager.navigateTo().mainPage();
		List<WebElement> tRows = driver.findElements(By.xpath("//tr[@name='entry']"));		
		for (int trIndex = 0; trIndex < tRows.size(); trIndex++) {
		    WebElement element = tRows.get(trIndex);
		    String locator = "//tr[" + (trIndex+2) +"]//td[%s]";
		    String lname = element.findElement(By.xpath(String.format(locator, 2))).getText();
		    String fname = element.findElement(By.xpath(String.format(locator, 3))).getText();
		    String em = "";
		    String ph = element.findElement(By.xpath(String.format(locator, 5))).getText().trim();
		    lst1.add(new ContactData().withFitstName(fname).withLastName(lname).withMainEmail(em).withHomePhone(ph));
		}
	  return lst1;
	}
	
	public SortedListOf<ContactData> getPhoneContacts(){
		SortedListOf<ContactData> lstSecond = new SortedListOf<ContactData>();
		manager.navigateTo().printPhonePage();
		List<WebElement> phoneRows = driver.findElements(By.xpath("(//tbody//tr)"));
		  for (int trIndex = 0; trIndex < phoneRows.size(); trIndex++) {
		  List<WebElement> phoneCels = driver.findElements(By.xpath("(//tr[" + (trIndex+1) + "]//td[@valign='top'])"));
		  int tdValue = 0;
			while (tdValue < phoneCels.size()){			
	  	      WebElement element = phoneRows.get(trIndex);
	          String locator = "//tr[" + (trIndex+1) +"]//td[%s]";   
	          String name = element.findElement(By.xpath(String.format(locator, tdValue+1)+"//b")).getText();
	          if (name.isEmpty()){
	        	  String fname = "";
		          String lname = "";
		          String em = "";
		          String ph = "";
		          lstSecond.add(new ContactData().withFitstName(fname).withLastName(lname).withMainEmail(em).withHomePhone(ph));
				  tdValue++;
	          } else {
	              String[] nameAr = name.split("\\s+");
	              String fname = nameAr[0];
	              String lname = nameAr[1];
	              String inf = element.findElement(By.xpath(String.format(locator, tdValue+1))).getText();
	              String[] mainStr = inf.split("\n");
		          int ind = mainStr[1].indexOf(" ");
		          String em = ""; 
		          String ph = mainStr[1].substring(ind+1).trim();
		          lstSecond.add(new ContactData().withFitstName(fname).withLastName(lname).withMainEmail(em).withHomePhone(ph));
		          tdValue++;
		      }  
			}
		  }
	  return lstSecond;
	}

	public ContactHelper createContact(ContactData cont, boolean formType) throws InterruptedException {
	    manager.navigateTo().newContactPage();
	    waitFormWithFirstnameInputPresence();
		contactInformationFilling(cont, formType);
	    submitContactCreation();
	    msBoxPresence();
	    moveBackOnHomePage();
	    rebuildCache();
		return this;
	}

	public ContactHelper modifyContact(ContactData cont, int index, boolean formType) throws InterruptedException {
		moveToContactInfoModification(index);
	    waitFormWithFirstnameInputPresence();
	    contactInformationFilling(cont, formType);
	    submitContactModification();
	    msBoxPresence();
	    moveBackOnHomePage();
	    waitCreatedContactRecordPresence(cont.getMainEmail());
	    rebuildCache();
		return this;
	}
	
	public ContactHelper deleteContact(int index) throws InterruptedException {
		moveToContactInfoModification(index);
	    waitFormWithFirstnameInputPresence();
	    submitContactDeleting();
        msBoxPresence();
	    moveBackOnHomePage();
	    rebuildCache();
	    return this;
	}
	
	public ContactHelper moveToContactInfoModification(int index) {
		selectContByInd(index);
		return this;
	}
	
	// --------------------------------------------------
	
	
	public ContactHelper submitContactCreation() {
		findAndClick(By.name("submit"));
		cachedCont = null;
		return this;
	}

	public ContactHelper contactInformationFilling(ContactData cont, boolean formType) {
		findAndEnter(By.name("firstname"), cont.getFirstName());
		findAndEnter(By.name("lastname"), cont.getLastName());
		findAndEnter(By.name("address"), cont.getAddress());
		findAndEnter(By.name("home"), cont.getHomePhone());
		findAndEnter(By.name("mobile"), cont.getMobilePhone());
		findAndEnter(By.name("work"), cont.getWorkPhone());
		findAndEnter(By.name("email"), cont.getMainEmail());
		findAndEnter(By.name("email2"), cont.getExtraEmail());
	    findAndSelect(By.name("bday"), cont.getBirthDay());
	    findAndSelect(By.name("bmonth"), cont.getBirthMonth());
	    findAndEnter(By.name("byear"), cont.getBirthYear());
	    if (formType != MODIFICATION ){
	       findAndSelect(By.name("new_group"), assGroupName());
	    }
	    findAndEnter(By.name("address2"), cont.getSecondAddress());
		findAndEnter(By.name("phone2"), cont.getHomeWebPage());
		return this;
	}
	
	private String assGroupName() {
		Random rnd = new Random();
		
		List<String> elem = new ArrayList<String>();
    	List<WebElement> groupList = driver.findElements(By.xpath("(//select[@name='new_group']//option)"));
    	for (WebElement li : groupList) {
			String title = li.getText();	
			elem.add(title);
		}
    	String[] elemList = elem.toArray(new String[elem.size()]);
    	int index = rnd.nextInt(elem.size());
		return elemList[index];
	}

	public ContactHelper submitContactModification() {
		findAndClick(By.xpath("(//input[@value='Update'])"));
		cachedCont = null;
		return this;
	}
	
	public ContactHelper submitContactDeleting() {
		findAndClick(By.xpath("(//input[@value='Delete'])"));
		cachedCont = null;
		return this;
	}
	
	public ContactHelper selectContByInd(int i) {
		findAndClick(By.xpath("(//tr[" + (i+2) + "]//a[contains(@href, 'edit.php')])"));
		return this;
	}
	
	public ContactHelper moveBackOnHomePage() {
		findAndClick(By.xpath("(//a[@href='index.php'])"));
		return this;
	}
	
	public void moveOnPrintPhonePage() {
		findAndClick(By.xpath("(//a[@href='view.php?all&print&phones'])"));
	}
	
	// Waiting methods
	public ContactHelper waitFormWithFirstnameInputPresence() throws InterruptedException {
		waitElement(By.xpath("(//form//input[@name='firstname'])"));
		return this;
	}
	
	public ContactHelper waitCreatedContactRecordPresence(String ContactEmail) throws InterruptedException {
		waitElement(By.xpath("(//input[contains(@accept, '" + ContactEmail + "')])"));
		return this;
	}
	
	//
	public int generateRandGroupInd(int i){
		Random rnd = new Random();
		return rnd.nextInt(i);
	}
}	
